﻿using IMall.Web.Models;
using IMall.Web.Models.ViewModels;
using IMall.Web.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace IMall.Web.Service
{
    /// <summary>
    /// 服务
    /// </summary>
    public class IMallService
    {
        IMallDbContext context = new IMallDbContext();

        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public ListModel GetListModel(int page = 1, string keyword = null)
        {
            ListModel model = new ListModel();

            var query = context.Commodity.Where(p=>p.State ==1).AsQueryable();
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                query = from p in query
                        where p.Type == keyword
                        select p;
            }
            var list = query.OrderBy(p => p.Price).Skip(model.PageSize * (page - 1)).Take(model.PageSize)
                .Select(p => new ListItemModel()
                {
                    Id = p.Id,
                    Icon = p.Icon,
                    Name = p.Name,
                    Price = p.Price.ToString()
                }).ToList();

            model.List = list;
            model.Page = page;
            model.Number = query.ToList().Count;
            int n = model.PageNumber;
            return model;
        }

        /// <summary>
        /// 获取商品信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public CommodityModel GetCommodity(string id, string userId)
        {
            var query = context.Commodity.AsQueryable();
            CommodityModel model = query.Where(p => p.Id == id)
                .Select(p => new CommodityModel()
                {
                    Id = p.Id,
                    Freight = p.Freight == 0 ? "卖家承担运费" : p.Freight.ToString() + " 元",
                    Icon = p.Icon,
                    Name = p.Name,
                    Price = p.Price.ToString()
                }).First();

            var list = context.Adress.Where(p => p.UserId == userId).ToList();

            model.Adress = new List<KeyValuePair<string, string>>();

            foreach (var item in list)
            {
                string s = AdressHelper.AdressToString(item);
                model.Adress.Add(new KeyValuePair<string, string>(item.Id, s));
            }

            return model;
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="id"></param>
        internal void Cancel(string id)
        {
            try
            {
                var order = context.Order.Where(p => p.Id == id).FirstOrDefault();
                if (order != null && order.State == 1)
                {
                    order.State = 0;
                    order.CompleteTime = DateTime.Now;
                }
                if (order != null)
                {
                    context.SaveChanges();
                }
            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        /// 确认订单
        /// </summary>
        /// <param name="id"></param>
        internal void Complete(string id)
        {
            try
            {
                var order = context.Order.Where(p => p.Id == id).FirstOrDefault();
                if (order != null && order.State == 3)
                {
                    order.CompleteTime = DateTime.Now;
                    order.State = 4;
                }
                if (order != null)
                {
                    context.SaveChanges();
                }
            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public User Login(User user)
        {
            var u = context.User.Where(p => p.Name == user.Name && p.Password == user.Password).FirstOrDefault();
            return u;
        }

        /// <summary>
        /// 支付
        /// </summary>
        /// <param name="id"></param>
        public void Pay(string id)
        {
            try
            {
                var order = context.Order.Where(p => p.Id == id).FirstOrDefault();
                if (order != null && order.State == 1)
                {
                    order.PaymentTime = DateTime.Now;
                    order.State = 2;
                }
                if (order != null)
                {
                    context.SaveChanges();
                }
            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="size"></param>
        /// <param name="adress"></param>
        /// <param name="userId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public string CreateOrder(string size, string adress, string userId, string id)
        {
            var price = context.Commodity.Where(p => p.Id == id).First().Price;
            Order order = context.Order.Create();
            order.Id = Guid.NewGuid().ToString();
            order.Size = size;
            order.State = 1;
            order.AdressId = adress;
            order.UserId = userId;
            order.CommodityId = id;
            order.CreatedTime = DateTime.Now;
            order.Number = 1;
            order.Price = price;
            try
            {
                context.Order.Add(order);
                context.SaveChanges();
            }
            catch (Exception e)
            {

            }
            return order.Id;
        }

        /// <summary>
        /// 获取订单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public OrderModel GetOrder(string id)
        {
            var order = context.Order.Where(p => p.Id == id).FirstOrDefault();
            var command = context.Commodity.Where(p => p.Id == order.CommodityId).FirstOrDefault();
            var adress = context.Adress.Where(p => p.Id == order.AdressId).FirstOrDefault();
            OrderModel model = new OrderModel()
            {
                Adress = AdressHelper.AdressToString(adress),
                AdressId = order.AdressId,
                CommandityPrice = command.Price,
                CommandityId = command.Id,
                CommandityIcon = command.Icon,
                CommandityFreight = command.Freight,
                CommandityName = command.Name,
                CompleteTime = order.CompleteTime,
                CreatedTime = order.CreatedTime,
                Id = order.Id,
                Number = order.Number,
                PaymentTime = order.PaymentTime,
                Price = order.Price,
                Size = order.Size,
                State = order.State,
            };

            return model;
        }

        public List<HistoryModel> GetHistory(string userId)
        {
            var order = context.Order.Where(p => p.UserId == userId)
                .Select(p => new HistoryModel()
                {
                    Id = p.Id,
                    CommodityId = p.CommodityId,
                    CommodityName = p.Commodity.Name,
                    CreatedTime = p.CreatedTime,
                    Number = p.Number,
                    Price = p.Price,
                    State = p.State,
                    UserId = userId,
                }).OrderByDescending(p => p.CreatedTime).ToList();
            return order;
        }
    }
}